<template>
    <div class="centerDialogBox">
        <van-form @submit="onSubmit">
            <van-cell-group inset>
                <!-- 通过 pattern 进行正则校验 -->
                <van-field
                    v-model="imgs"
                    name="uploader"
                    label="头像"
                    :rules="[{ validator, message: '请输入正确内容' }]"
                >
                    <template #input>
                        <img class="dataimg" :src="imgs" @click="updateImg" />
                    </template>
                </van-field>
                <!-- 通过 validator 进行函数校验 -->
                <van-field
                    v-model="data.username"
                    name="username"
                    placeholder="请输入昵称"
                    label="昵称"
                    :rules="[{ validator: validatorUsername, message: '请输入正确内容' }]"
                />
                <van-field
                    v-model="gender"
                    is-link
                    readonly
                    name="gender"
                    label="性别"
                    placeholder="点击选择性别"
                    @click="showPicker = true"
                />
                <van-popup v-model:show="showPicker" position="bottom">
                    <van-picker :columns="columns" @confirm="onConfirm" @cancel="showPicker = false" />
                </van-popup>
                <van-field
                    v-model="data.tag"
                    name="tag"
                    placeholder="请输入个性签名"
                    label="个签"
                    :rules="[{ validator: validatorTag, message: '请输入正确内容' }]"
                />
            </van-cell-group>
            <div style="margin: 16px">
                <van-button round block type="primary" native-type="submit"> 提交 </van-button>
                <br />
                <van-button round block type="danger" @click="close"> 取消 </van-button>
            </div>
        </van-form>
        <input class="uploadBox" type="file" style="display: none" @change="uploadJPG" />
    </div>
</template>
<script lang="ts" setup>
import { showNotify, showToast } from "vant"
import { onMounted, ref } from "vue"
import { saveImg,updateCenterType,updateCenter } from "../api"
import { InputHTMLAttributes } from "vue"
// import { FieldRuleValidator, closeToast, showLoadingToast } from "vant"
const emits = defineEmits(["showCenter","Init"])
const data = ref<updateCenterType>({
    id: undefined,
    img: "",
    username: "",
    gender: undefined,
    tag: ""
})
const imgs=ref('')
const temp=ref(import.meta.env.VITE_ENV==='development'?"http://localhost:9001/static/":'http://49.232.228.40:9001/static/')
const gender = ref("男")
const showPicker = ref(false)
const columns = [
    { text: "男", value: 1 },
    { text: "女", value: 2 }
]
// const pattern = /\d{6}/

// 校验函数返回 true 表示校验通过，false 表示不通过
const validator = (val: any) => {
    if (val === "" || !val) {
        return `请上传头像`
    }
    return true
}
const updateImg = () => {
    if (document.all) {
        ;(document.getElementsByClassName("uploadBox")[0] as HTMLElement).click()
    } else {
        // 其它浏览器
        let e = document.createEvent("MouseEvents")
        e.initEvent("click", true, true)
        document.getElementsByClassName("uploadBox")[0].dispatchEvent(e)
    }
}
const validatorTag = (val: string) => {
    console.log(val, "tag")
    if (val.trim() === "") {
        return "个签不合法"
    }
    if (val.length > 50) {
        return `个签不得超过50个字符`
    }
    return true
}
const validatorUsername = (val: string) => {
    console.log(val, "username")
    if (val.trim() === "") {
        return `昵称不合法`
    }
    return true
}
const uploadJPG = (e: any) => {
    let file = e.target.files[0]
    if (file.type !== "image/jpeg" && file.type !== "image/png") {
        showToast("请上传 jpg/png 格式图片")
        ;(document.getElementsByClassName("uploadBox")[0] as InputHTMLAttributes).value = ""
        return
    }
    // const formData = new FormData()
    // formData.append("file", file)
    let reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = function (_target) {
        let img = new Image()
        img.src = this.result as string
        img.onerror = function () {
            // that.$message.error('上传的图片已损坏，请重新选择上传');
            //匹配的load进行false操作
            // that.changeLoding();
            return false
        }
        img.onload = async function () {
            const formData = new FormData()
            formData.append("file", file)
            let res = await saveImg(formData)
            if (res.code === 0) {
                imgs.value=temp.value+res.body
                data.value.img=res.body
            } else {
                (document.getElementsByClassName('uploadBox')[0] as InputHTMLAttributes).value = '';
                return
            }
        }
    }
}

const close = () => {
    emits("showCenter")
}

const onSubmit = async (values: any) => {
    if(values){
        console.log(data.value)
        let res=await updateCenter(data.value)
        console.log(res)
        if(res.code===0){
            showNotify({ type: "primary", message: "修改成功!" })
            localStorage.setItem("userInfo",JSON.stringify(res.body))
             emits("Init")
             emits("showCenter")
        }else{
            showNotify({ type: "primary", message: "修改失败!" }) 
        }
    }
}
const onConfirm = ({ selectedOptions }: any) => {
    data.value.gender = selectedOptions[0]?.value
    gender.value = selectedOptions[0]?.text
    showPicker.value = false
}
onMounted(() => {
    data.value = JSON.parse(localStorage.getItem("userInfo")!)
    console.log(data.value)
    if(data.value.gender===1){
        gender.value="男"
    }else{
        gender.value="女"
    }
    if (import.meta.env.VITE_ENV === "development") {
        imgs.value = "http://localhost:9001/static/" + data.value.img
    }else{
        imgs.value="http://49.232.228.40:9001/static/"+data.value.img
    }
})
</script>
<style lang="less" scoped>
.centerDialogBox {
    position: fixed;
    top: 0px;
    left: 0px;
    background-color: rgba(3, 0, 0, 0.3);
    width: 100vw;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    .dataimg {
        width: 50px;
        height: 50px;
    }
}
</style>
